package com.hcr.elecident;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.webkit.WebView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.baidu.aip.face.stat.Ast;
import com.baidu.idl.face.platform.FaceStatusEnum;
import com.baidu.idl.face.platform.ui.FaceDetectActivity;
import com.baidu.idl.face.platform.utils.Base64Utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

public class FaceDetectExpActivity extends FaceDetectActivity {

    @Override
    public void onDetectCompletion(FaceStatusEnum status, String message,
                                   HashMap<String, String> base64ImageMap) {
        if (mIsCompletion) {
            return;
        }

        onRefreshView(status, message);

        if (status == FaceStatusEnum.OK) {


            mIsCompletion = true;
//            String fileName = saveImage(base64ImageMap);
            Map<String,String> map = saveImage(base64ImageMap);
            String fileName = map.get("fileName");
            String name = getIntent().getStringExtra("name");
            String idnum = getIntent().getStringExtra("num");

            String phone = getIntent().getStringExtra("phone");  // 前端识别传过来的手机号码
            String base64 = map.get("base64");

//            System.out.println("+++++++++++++++++++++"+base64);

//            if (MainActivity.isPase(name,idnum,base64)){
            if (true){

                ActivityManager.getActivityManager().popAllActivityExceptOne(PageActivity.class);

                // 跳转result
                final Intent it = new Intent(this, PageActivity.class);
                it.putExtra("name",name);
                it.putExtra("num",idnum);
                it.putExtra("fileName",fileName);


                // 全局信息
                WelcomeActivity.myName = name;
                WelcomeActivity.myNum = idnum;
                WelcomeActivity.myPhoto = fileName;

                saveData(phone,name,idnum,fileName);

                System.out.println("FileName:============="+fileName);
                startActivity(it);
                finish();
            } else {
                Toast.makeText(this,"人脸识别失败，请重试！",Toast.LENGTH_SHORT).show();
                finish();
            }




        }
        Ast.getInstance().faceHit("detect");
    }


    /**
     * 保存数据
     * @param phone
     * @param name
     * @param num
     * @param photo
     */
    public void saveData(String phone,String name,String num,String photo){
        SharedPreferences.Editor editor = getSharedPreferences(WelcomeActivity.TEMP_DATA,MODE_PRIVATE).edit();
        editor.putString(phone,name+"@"+num+"@"+photo);
        editor.commit();
    }


    @Override
    public void finish() {
        super.finish();
    }

    private void onRefreshView(FaceStatusEnum status, String message) {
        switch (status) {
            case OK:
                onRefreshTipsView(false, message);
                mTipsBottomView.setText("");
                mFaceDetectRoundView.processDrawState(false);
                onRefreshSuccessView(true);
                break;
            case Detect_PitchOutOfUpMaxRange:
            case Detect_PitchOutOfDownMaxRange:
            case Detect_PitchOutOfLeftMaxRange:
            case Detect_PitchOutOfRightMaxRange:
                onRefreshTipsView(true, message);
                mTipsBottomView.setText(message);
                mFaceDetectRoundView.processDrawState(true);
                onRefreshSuccessView(false);
                break;
            default:
                onRefreshTipsView(false, message);
                mTipsBottomView.setText("");
                mFaceDetectRoundView.processDrawState(true);
                onRefreshSuccessView(false);
        }
    }

    private void onRefreshTipsView(boolean isAlert, String message) {
        if (isAlert) {
            if (mTipsIcon == null) {
                mTipsIcon = getResources().getDrawable(R.mipmap.ic_warning);
                mTipsIcon.setBounds(0, 0, (int) (mTipsIcon.getMinimumWidth() * 0.7f),
                        (int) (mTipsIcon.getMinimumHeight() * 0.7f));
                mTipsTopView.setCompoundDrawablePadding(15);
            }
            mTipsTopView.setBackgroundResource(R.drawable.bg_tips);
            mTipsTopView.setText(R.string.detect_standard);
            mTipsTopView.setCompoundDrawables(mTipsIcon, null, null, null);
        } else {
            mTipsTopView.setBackgroundResource(R.drawable.bg_tips_no);
            mTipsTopView.setCompoundDrawables(null, null, null, null);
            if (!TextUtils.isEmpty(message)) {
                mTipsTopView.setText(message);
            }
        }
    }

    private void onRefreshSuccessView(boolean isShow) {
        if (mSuccessView.getTag() == null) {
            Rect rect = mFaceDetectRoundView.getFaceRoundRect();
            RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) mSuccessView.getLayoutParams();
            rlp.setMargins(
                    rect.centerX() - (mSuccessView.getWidth() / 2),
                    rect.top - (mSuccessView.getHeight() / 2),
                    0,
                    0);
            mSuccessView.setLayoutParams(rlp);
            mSuccessView.setTag("setlayout");
        }
        mSuccessView.setVisibility(isShow ? View.VISIBLE : View.INVISIBLE);
    }

    private Map<String,String> saveImage(HashMap<String, String> imageMap) {
        Map<String,String> res = new HashMap<>();
        Set<Map.Entry<String, String>> sets = imageMap.entrySet();
        Bitmap bmp = null;

//        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
//        String fileName = format.format(new Date()) + ".jpg";
        String fileName = System.currentTimeMillis()+".jpg";
        mImageLayout.removeAllViews();
        for (Map.Entry<String, String> entry : sets) {
            bmp = base64ToBitmap(entry.getValue());

            // 设置照片截取，防止黑框
            bmp = Bitmap.createBitmap(bmp, bmp.getWidth()/6, bmp.getHeight() /8, bmp.getWidth()*2/3, bmp.getHeight()*2 / 3);
            fileName = saveBitmap(bmp, fileName);
            res.put("fileName",fileName);
            res.put("base64",bitmapToBase64(bmp));
        }

        return res;

    }



    private static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64Utils.decode(base64Data, Base64Utils.NO_WRAP);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    public String saveBitmap(Bitmap bitmap, String bitName) {
        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
        } else { // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName;
        }
        file = new File(fileName);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
                out.flush();
                out.close();
// 插入图库
                MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), bitName, null);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 发送广播，通知刷新图库的显示
        this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));

        return fileName;
    }

    /**
     * bitmap转为base64
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
